package org.example.service.impl;

import io.jsonwebtoken.Claims;
import org.example.redis.RedisCache;
import org.example.service.ILoginService;
import org.example.util.JwtUtil;
import org.example.vo.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

	private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

	@Autowired
	private RedisCache redisCache;

	// 也可写在yml中，然后引入
	private static String header = "Authorization";

	private static String LOGIN_TOKEN_KEY = "login_tokens:";

	private final static long expireTime = 60L;

	@Override
	public LoginUser getLoginUser(HttpServletRequest request) {
		String token = getToken(request);
		if (null == token || "".equals(token)) { // token为空，直接返回
			return null;
		}
		Claims claims = JwtUtil.parseToken(token);
		if (null == claims) { // token解析不出信息，直接返回
			return null;
		}
		String userKey = JwtUtil.getUserKey(claims);
		String tokenKey = getTokenKey(userKey);
		boolean isLogin = redisCache.exists(tokenKey);
		if (!isLogin) { // token已不在缓存中，直接返回
			return null;
		}
		// 从缓存中获取用户信息
		LoginUser loginUser = redisCache.getCacheObject(tokenKey);
		return loginUser;
	}

	@Override
	public void verifyToken(LoginUser loginUser) {
		refreshToken(loginUser);
	}

	// 刷新token
	private void refreshToken(LoginUser loginUser) {
		long currented = System.currentTimeMillis();
		loginUser.setLoginTime(currented);
		loginUser.setExpireTime(currented + expireTime * 1000);
		String userKey = getTokenKey(loginUser.getToken());
		logger.info("刷新token:【{}】,{}_{}", loginUser.getToken(), expireTime, TimeUnit.MINUTES);
		// 60分钟失效
		redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
	}

	private String getToken(HttpServletRequest request) {
		String token = request.getHeader(header);
		return token;
	}

	private String getTokenKey(String token) {
		return LOGIN_TOKEN_KEY + token;
	}
}
